package org.gwtunclutter.client;

import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;

/**
 * Date: Sep 7, 2007
 * Time: 12:27:25 AM
 *
 * @author Alex
 */
public class ListenerFactory {

  /**
   * Creates a keyboad listener that listens for the Enter key press event.
   * @param command The action to be executed when the Enter key is pressed.
   */
  public static KeyboardListener enterKeyListener(final Command command) {
    return new KeyboardListenerAdapter() {
      public void onKeyPress(Widget sender, char keyCode, int modifiers) {
        if (keyCode == KEY_ENTER)
          command.execute();
      }
    };
  }

  /**
   * Creates a keyboad listener that listens any key press event.
   * In some browsers non-print characters don't generate key press
   * events - for these you can use key up and key down events.
   * @param command The action to be executed when any key is pressed.
   */
  public static KeyboardListener keyPressListener(final Command command) {
    return new KeyboardListenerAdapter() {
      public void onKeyPress(Widget sender, char keyCode, int modifiers) {
        command.execute();
      }
    };
  }

  /**
   * Creates a keyboad listener that handles key up events.
   * @param command The action to be executed on key up events.
   */
  public static KeyboardListener keyUpListener(final Command command) {
    return new KeyboardListenerAdapter() {
      public void onKeyUp(Widget sender, char keyCode, int modifiers) {
        command.execute();
      }
    };
  }

  public static ClickListener clickListener(final Command command) {
    return new ClickListener() {
      public void onClick(Widget sender) {
        command.execute();
      }
    };
  }

  public static ChangeListener changeListener(final Command command) {
    return new ChangeListener() {
      public void onChange(Widget sender) {
        command.execute();
      }
    };
  }

  /**
   * Similar to using ChangeListener, except this keyboard listener
   * proactively looks for changes in the given textbox on every keystroke,
   * as opposed to waiting until the textbox loses focus.
   */
  public static KeyboardListener textChangeListener(final TextBoxBase textBox, final Command command) {
    return new KeyboardListenerAdapter() {
      public void onKeyPress(Widget sender, char keyCode, int modifiers) {
        final String oldValue = textBox.getText();
        // fire this command outside the thread, to let the key press event propagate
        // and finish modifying the text
        DeferredCommand.addCommand(new Command() {
          public void execute() {
            if (!textBox.getText().equals(oldValue))
              command.execute();
          }
        });
      }
    };
  }
}
